Switch = {
    name = "switch",
    props = {
        allowSwitchOff = true
    },
    gets = {

    },
    sets = {

    },
    dependencies = {
        Button
    }
}
SwitchEvent = RegisterEvents{
    "SwitchOn",
    "SwitchOff"
}

-- 点击触发开关的开启和关闭
local function doSwitch(self)
    local isOn = not self.switchOn
    if not isOn and not self.allowSwitchOff then
        return
    end
    self:switch(isOn)
end
function Switch:switch(isOn)
    self.switchOn = isOn
    if self.switchOn then
        self:emit(SwitchEvent.SwitchOn, self)
    else
        self:emit(SwitchEvent.SwitchOff, self)
    end
end
function Switch:ctor()
    self:onClick(doSwitch, self)
end

local function ballLeft(ball)
    Tween.new(ball):to(0.1, {x = 10}):start()
end
local function ballRight(ball)
    Tween.new(ball):to(0.1, {x = 35}):start()
end

function Switch:onSwitchOn(fn, target)
    self:on(SwitchEvent.SwitchOn, fn, target)
end

function Switch:onSwitchOff(fn, target)
    self:on(SwitchEvent.SwitchOff, fn, target)
end

function Node.Switch(str)
    local node = Node.Layout()
    node:addComponent(Switch)
    node.layoutSizeMode = LayoutSizeMode.Stretch
    node.name = "Switch"
    node.layoutType = LayoutType.Horizontal

    Node.Label(str):addTo(node).touchSwallowed = false

    local pad = Node.Scale9("circle20"):wh(45, 20):axy(0, 0.5):addTo(node)
    pad.touchSwallowed = false
    pad.name = "switch pad"

    local ball = Node.Sprite("circle16"):addTo(pad):xy(10, 0)
    ball.color = Color.blue
    ball.name = "switch ball"
    ball:setNativeSize()
    ball.touchSwallowed = false
    node:onSwitchOn(ballRight, ball)
    node:onSwitchOff(ballLeft, ball)
    return node
end
